package edu.pku.sei.modeler.uml.actions;

import org.eclipse.jface.action.Action;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.PlatformUI;

import edu.pku.sei.modeler.exceptions.FactoryNotFoundException;
import edu.pku.sei.modeler.exceptions.PackageNotFoundException;
import edu.pku.sei.modeler.model.common.AbstractFactory;
import edu.pku.sei.modeler.model.common.AbstractPackage;
import edu.pku.sei.modeler.model.common.ModelRegistry;
import edu.pku.sei.modeler.model.core.MetaPackage;
import edu.pku.sei.modeler.model.structure.MetaDiagram;
import edu.pku.sei.modeler.project.ProjectRegistry;
import edu.pku.sei.modeler.uml.modelHelper.ModelFactory;

public class DeleteDiagramAction extends Action {
	private Object obj;
	public DeleteDiagramAction(){
		super();
		this.setText("delete");
		this.setImageDescriptor(PlatformUI.getWorkbench().getSharedImages().
				getImageDescriptor(ISharedImages.IMG_OBJS_ERROR_TSK));
	}
	public void setTreeObj(Object obj) {
		this.obj = obj;
	}
	public void run(){
		if (obj instanceof MetaDiagram){
			MetaDiagram diagram = (MetaDiagram)obj;
			if (MessageDialog.openConfirm(null, "Confirm", "Sure to delete?") == false) {
				return;
			}
			ProjectRegistry.getDefault().getProjectByDiagram(diagram)
			.closeDiagram(diagram, false);
			MetaPackage mPackage = (MetaPackage)diagram.getContainer();
			mPackage.getDiagrams().remove(diagram);
			
			ModelFactory factory;
			try {
				factory = (ModelFactory) ModelRegistry.getRegistry().getFactory(diagram.getModel());
				AbstractPackage pkg = ModelRegistry.getRegistry().getPackageByFactory(factory);
				pkg.removeObjByID(diagram.getElementID());
			} catch (IllegalArgumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (FactoryNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (PackageNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			

		}
	}
	
}
